<template>
  <panel-head :route="route"/>
 <!-- 新增按钮 -->
  <div class="btns">
    <el-button type="primary" @click="openDialog(null)" size="small">
    <el-icon><Plus /></el-icon>
    新增
  </el-button>
  </div>
  <!-- 菜单权限列表 -->
  <el-table 
  :data="tableData.list" 
  style="width: 100%"
  >
    <el-table-column prop="id" label="id" />
    <el-table-column prop="name" label="昵称" />
    <el-table-column prop="permissionName" label="菜单权限" width="500px" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button size="small" @click="openDialog(scope.row)">
          编辑
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 新增/编辑权限弹窗 -->
  <el-dialog 
  v-model="dialogFormVisible" 
  title="添加权限" 
  width="500" 
  :before-close="beforeClose">
    <el-form 
    ref="formRef"
    :model="dialogForm"
    label-position="left"
    label-width="100px"
    :rules="rules"
    >
    <!-- 此标签隐藏 -->
      <el-form-item v-show="false" label=" id" prop="id">
        <el-input v-model="dialogForm.id" />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="dialogForm.name" placeholder="请输入权限名称"/>
      </el-form-item>
      <el-form-item label=" 权限" prop="permissions">
          <el-tree
            ref="treeRef"
            style="max-width: 600px"
            :data="permissionData"
            show-checkbox
            node-key="id"
            :default-expanded-keys="[2]"
            :default-checked-keys="defaultCheckedKeyData"
          />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button 
        type="primary" plain
        @click="confirm(formRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 分页 -->
 <div class="pagination-info">
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="paginationData.pageNum"
        :page-size="paginationData.pageSize"
        layout="total, prev, pager, next"
        :total="tableData.total"
        @current-change="handleCurrentChange"
      />
    </div>
 </div>
</template>

<script setup>
import {ref,reactive, onMounted, nextTick} from 'vue'
import {userGetmenu,userSetmenu,menuList} from '../../../api'
import { ElMessage } from 'element-plus'
import {useRoute} from 'vue-router'

//权限数据,调用接口获取
const permissionData=ref([])

onMounted(()=>{
  //渲染菜单权限列表
  getListData()

  //获取权限数据
  userGetmenu().then((data)=>{
   permissionData.value=data.data
  //  console.log(permissionData.value)
  })
})

//treeRef实例用于获取表单的权限数据
const treeRef = ref()
const formRef = ref()
const route=useRoute()

//控制新增对话框弹出关闭
const dialogFormVisible=ref(false)
const dialogForm = reactive({
  name: '',
  permissions:'',
  id:''
})
//弹窗打开
const defaultCheckedKeyData=ref([2,4,5])
const openDialog=(rowData)=>{
  dialogFormVisible.value=true
  // 弹窗打开是异步的
  nextTick(()=>{
    if(rowData){
      // console.log(rowData,'rowData')
      Object.assign(dialogForm,{id:rowData.id,name:rowData.name})
      treeRef.value.setCheckedKeys(rowData.permission)
    }
  })
}
//对话框关闭前的回调
const beforeClose=()=>{
  //重置表单
  formRef.value.resetFields()
  treeRef.value.setCheckedKeys(defaultCheckedKeyData.value)
  //关闭弹窗
  dialogFormVisible.value=false
  //重新渲染列表
  getListData()
}
//表单校验规则
const rules = reactive({
  name: [{required: true, message: '请填写名称', trigger: 'blur' }]
})
//提交表单
const confirm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      //表单验证合法，提交菜单权限修改/新增请求
      //获取表单的权限数据
      const permissions=JSON.stringify(treeRef.value.getCheckedKeys())
      userSetmenu({name:dialogForm.name,permissions,id:dialogForm.id}).then((data)=>{
        if(data.code===10000){
          ElMessage.success('提交成功！')
          beforeClose()
        }else{
          ElMessage.danger('错误，请稍后再试')
        }
      })
      
    }else{
      console.log('菜单权限修改/新增失败！')
    }
  })
}

const paginationData=reactive({
  pageNum:1,
  pageSize:10
})
const tableData=ref({
  list:[],
  total:0
})
//获取菜单权限列表（封装方法）
const getListData=()=>{
  menuList(paginationData).then((data)=>{
    // console.log(data)
    tableData.value=data.data
  })
}

const handleCurrentChange=(val)=>{
  paginationData.pageNum=val
  getListData()
}
</script>

<style lang="less" scoped>
.pagination-info{
  background-color: #fff;
}
.btns{
  padding: 7px 10px;
  background-color: #fff;
}
</style>
